package cn.memset.code.lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;

public class LambdaExample {
    public static void main(String[] args) {
        sortProvincesWithLambda();
    }

    public static void createThreadWithAnonymousClass() {
        // Runnable 接口名。通过匿名类的方式，构造了一个 Runnable 的实例。
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread is running");
            }
        });

        t.start();
    }

    public static void createThreadWithLambda() {
        // 在Java 8中，Runnable 是一个函数式接口，因此我们可以使用 lambda 表达式来实现它。
        Thread t = new Thread(() -> {
            System.out.println("Thread is running");
        });

        t.start();
    }

    public static void sortProvincesWithAnonymousClass() {
        List<String> list = Arrays.asList("Guangdong", "Zhejiang", "Jiangsu", "Xizang", "Fujian", "Hunan", "Guangxi");

        list.sort(new Comparator<String>() {
            @Override
            public int compare(String first, String second) {
                int lenDiff = first.length() - second.length();
                return lenDiff == 0 ? first.compareTo(second) : lenDiff;
            }
        });

        list.forEach(s -> System.out.println(s));
    }

    public static void sortProvincesWithLambda() {
        List<String> list = Arrays.asList("Guangdong", "Zhejiang", "Jiangsu", "Xizang", "Fujian", "Hunan", "Guangxi");

        // 下面的参数列表 first 和 second ，即方法 Comparator.compare 的参数列表
        list.sort((first, second) -> {
            int lenDiff = first.length() - second.length();
            return lenDiff == 0 ? first.compareTo(second) : lenDiff;
        });

        list.forEach(s -> System.out.println(s));
    }
}
